#include <linux/limits.h>
#include <stdio.h>
#include "DirTraverse.h"

void
help(const char *arg0)
{
    printf(
        "%s -r|-R -f|-F DIRPATH\n"
        "-r|-R; 控制着是否递归;r,递归;R,不递归;默认 -r.\n"
        "-f|-F; 遍历函数的类型;-f,普通函数;-F,仿函数;默认 -f.\n",
        arg0
    );
}

enum {
    FUNCTION = 0,
    FUNCTOR
};

void
traversefunc(const struct dirent *entry)
{
    struct stat fileStat;
    int ret = lstat(entry->d_name,&fileStat);
    if (ret != 0) {
        fprintf(stderr,"ERROR;lstat(%s): %m",entry->d_name);
        return ;
    }
    printf("INFO;file: %s;size: %zu\n",entry->d_name,fileStat.st_size);
    return ;
}

struct TraverseFunctor {
    void
    operator()(const struct dirent *entry) const {
        traversefunc(entry);
        return ;
    }
};

int
main(int argc,char *argv[])
{
    bool recursive = true;
    int traverseFuncType = FUNCTION;
    const char *dir = 0;

    int ret;
    while ((ret = getopt(argc,argv,":rRfF")) != -1) {
        switch (ret) {
        case 'r':
            recursive = true;
            break;
        case 'R':
            recursive = false;
            break;
        case 'f':
            traverseFuncType = FUNCTION;
            break;
        case 'F':
            traverseFuncType = FUNCTOR;
            break;
        default:
            break;
        }
    }
    if (optind < argc)
        dir = argv[optind];
    if (dir == 0) {
        help(argv[0]);
        return 1;
    }
    printf("INFO;dir: %s;%s;%s\n",dir,recursive ? "recursive" : "norecursive",
        traverseFuncType == FUNCTION ? "function" : "functor");
    char cwd[PATH_MAX];
    printf("INFO;pwd: %s\n",getwd(cwd));
    DirTraverse dirTraverse;
    dirTraverse.setRecursive(recursive);
    if (traverseFuncType == FUNCTOR) {
        TraverseFunctor functor;
        dirTraverse.traverse(dir,functor);
    } else {
        dirTraverse.traverse(dir,traversefunc);
    }
    printf("INFO;pwd: %s\n",getwd(cwd));
    return 0; 
}

